# -*- coding: utf-8 -*-
"""
Module Description: 封装了请求对象和响应对象
Date: 2018/3/8
Author:Bai Jin Ping
"""
import copy
import utils.json_utils as json
from app.const.lang_enum import LangEnum
from app.const.lang.translate import translater as __
from framework.firefly_dc.global_errcode import GlobalErrCode


class Request(object):
    """请求对象"""
    def __init__(self, request_args):
        # 请求参数
        self.args = request_args

        # 上下文对象
        self.ctx = None

    def get_attribute(self, attr_name, default=None):
        """
        获得请求属性
        :param attr_name: 属性名
        :param default: 若属性不存在,返回的默认值
        :return:
        """
        return self.args.get(attr_name, default)

    def set_attribute(self, attr_name, val):
        """
        设置请求属性
        :param attr_name: 属性名
        :param val: 属性值
        :return:
        """
        self.args[attr_name] = val

    @property
    def action_id(self):
        """接口号"""
        action_id = self.get_attribute('actionid')
        return 0 if action_id is None else int(action_id)


class Response(object):
    """响应对象"""

    def __init__(self, stat=GlobalErrCode.SUCCESS, action_id=0, info='', lang=LangEnum.Simplified):
        """
        :param stat: int 返回状态
        :param action_id: int 对应请求的接口号
        """
        # 响应状态码
        self.stat = stat
        # 接口号
        self.action_id = action_id
        # 响应信息
        self.info = info
        # 语言类型
        self.lang = lang

        self.response = dict()

        # 增加头部返回
        self.headers = dict()
        # 增加会话相关参数
        self.session = dict()

    def set_stat(self, stat):
        """
        设置响应状态码
        :param stat: 状态码
        """
        self.stat = stat

    def set_action_id(self, action_id):
        """
        设置接口号(只能设置一次)
        :param action_id: 接口号
        """
        assert self.action_id == 0
        self.action_id = action_id

    def set_info(self, info, stat, force_clear=False):
        """
        设置响应信息
        :param info: 响应信息
        :param stat: 响应状态码
        :param force_clear: 是否完全清理掉返回数据
        """
        self.info = info
        self.set_stat(stat)

        if force_clear:
            self.clear()

    def set_attribute(self, key, value):
        """
        新增响应数据
        :param key: 键
        :param value: 值
        """
        self.response[key] = value

    def set_attribute_dict(self, val_dict):
        """
        批量添加响应数据
        :param val_dict: 响应数据字典
        """
        self.response.update(val_dict)

    def clear(self):
        """
        删除所有返回字段
        """
        self.response.clear()

    def set_lang(self, lang):
        """
        设置语言类型
        :param lang: 语言类型（中文简体 zh-cn，中文繁体 zh-tw，英文 en）
        """
        self.lang = lang

    def format_info_of_language(self, info):
        """根据语言类型返回相应语言信息"""
        return_info = info

        if isinstance(info, (str, unicode)):
            # 如果不全是字母,则直接使用该字符串 -- unicode的isalpha,中文会被判断为字母
            if not str(info).isalpha():
                return info
            else:
                # return_info = __(info, self.lang)
                pass


        elif isinstance(info, tuple):
            return_info = __(info[0], self.lang)
            if not return_info:
                return_info = info[0]
            return_info = return_info % info[1:]

        return return_info

    def serialize(self):
        """
        序列化响应结果
        :return string
        """
        rtn_dict = copy.deepcopy(self.response)
        if 'Stat' not in rtn_dict:
            rtn_dict['Stat'] = self.stat
        if 'Info' not in rtn_dict:
            rtn_dict['Info'] = self.info
        rtn_dict['Info'] = self.format_info_of_language(rtn_dict['Info'])
        return json.dumps(rtn_dict)

    def set_headers(self, key, value):
        """
        增加头部返回
        :param key: 键
        :param value: 值
        """
        self.headers[key] = value

    def set_session(self, key, value):

        """
        增加session参数
        :param key: 键
        :param value: 值
        """
        self.session[key] = value
